/*
 * Copyright (c) 2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#pragma pack(1)
#define SHARE_MEM_KEY_PATH  "/usr/lib"
#define MSG_QUEUE_KEY_PATH  "/usr/bin"
static int SHARE_MEM_KEY_ID_READ[] = {
    0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,
};
static int SHARE_MEM_KEY_ID_WRITE[] = {
    0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
};
static int MSG_QUEUE_KEY_ID_READ[] = {
    0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
};
static int MSG_QUEUE_KEY_ID_WRIRE[] = {
    0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
};

struct msg{
    unsigned int len;
    unsigned char mtext[896];
};
struct msgbuf{
    long mtype;
    struct msg block;
};
int msgId = -1 ;
int data_len = 896 ;
long data_type = 886;
void Get_CtrlC_handler(int sig);
int main()
{
	signal(SIGINT, Get_CtrlC_handler);
	struct msgbuf writebuf ;
	memset(&writebuf, 0, sizeof(struct msgbuf));
	writebuf.mtype = data_type ;
	writebuf.block.len = data_len;
	for(int i=0; i<data_len; i++){
		writebuf.block.mtext[i] = i ;
	}

	key_t tmp_key = ftok(MSG_QUEUE_KEY_PATH, MSG_QUEUE_KEY_ID_WRIRE[0]);
	msgId = msgget(tmp_key, IPC_CREAT|0666);
	if(msgId<0) {
		printf("msgget failed\n");
	}
	printf("msgId=%d,tmp_key=%#x\n",msgId, tmp_key);
	while(1)
	{
		data_len = msgsnd(msgId, &writebuf, sizeof(writebuf.block), 0);
		printf("send %d\n",data_len);
		usleep(1000*1000);
		writebuf.block.mtext[0]++ ;
		if(writebuf.block.len-- == 0)
			writebuf.block.len = 896 ;
	}

    return 0;
}

void Get_CtrlC_handler(int sig) {
//	if(msgctl(msgId, IPC_RMID, 0) == -1) //let recv thread to delete queue id
//	{
//		 fprintf(stderr, "msgctl(IPC_RMID) failedn");
//		 exit(EXIT_FAILURE);
//	}
	exit(0);
//	char c;
//
//	signal(sig, SIG_IGN);
//	printf("\ndo you be sure exit ? [y/n]: ");
//
//	c = getchar();
//	if (c == 'y' || c == 'Y') {
//		printf("exit ok\n");
//		exit(0);
//	}else
//		signal(SIGINT, Get_CtrlC_handler);
//	getchar();
}

